package com.project.easy.common.db.mybatisplus.core.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.project.easy.common.db.mybatisplus.core.service.IQueryCurrentUser;
import com.project.easy.common.db.mybatisplus.core.dto.BaseCommonBean;
import com.project.easy.common.db.mybatisplus.core.dto.BaseRefCommonBean;
import org.apache.ibatis.reflection.MetaObject;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Objects;

/**
 * @author GreatorMan.cool
 * @copyright: Copyright (c) 2020
 * @company: 扬起科技有限公司
 * @date 2021/10/30 22:00
 * @description: 持久化自动填充
 */
@Component
public class FullFieldValueHandler implements MetaObjectHandler {

    private static final org.slf4j.Logger LOG = LoggerFactory.getLogger(FullFieldValueHandler.class);

    @Autowired(required = false)
    private IQueryCurrentUser iQueryCurrentUser;

    @Override
    public void insertFill(MetaObject metaObject) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("开始写入填充数据：{}", metaObject.getOriginalObject());
        }
        Object originalObject = metaObject.getOriginalObject();
        if (!Objects.isNull(originalObject)) {
            if (originalObject instanceof BaseCommonBean) {
                //一般表的维护
                this.strictInsertFill(metaObject, "createTime", Date.class, new Date());
                if (!Objects.isNull(iQueryCurrentUser)) {
                    this.strictInsertFill(metaObject, "createUser", String.class, iQueryCurrentUser.query().getAcc());
                }
            } else if (originalObject instanceof BaseRefCommonBean) {
                //中间表时间维护
                this.strictInsertFill(metaObject, "createTime", Date.class, new Date());
            }
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("开始更新填充数据：{}", metaObject.getOriginalObject());
        }
        Object originalObject = metaObject.getOriginalObject();
        if (!Objects.isNull(originalObject) && originalObject instanceof BaseCommonBean) {
            this.strictUpdateFill(metaObject, "updateTime", Date.class, new Date());
            if (!Objects.isNull(iQueryCurrentUser)) {
                this.strictUpdateFill(metaObject, "updateUser", String.class, iQueryCurrentUser.query().getAcc());
            }
        }
    }
}
